//app.js
import Dialog from '/miniprogram/miniprogram_npm/vant-weapp/dialog/dialog';
const moment = require('/utils/moment.min.js')
let livePlayer = requirePlugin('live-player-plugin');
App({
  // 获取直播间分享参数
  onShow(options) {
    if (options) {
      // 分享卡片入口场景才调用getShareParams接口获取以下参数
      if (options.scene == 1007 || options.scene == 1008 || options.scene == 1044) {
        livePlayer.getShareParams()
          .then(res => {
            wx.setStorageSync('shareOpenid',res.share_openid);
            console.log('get room id', res.room_id) // 房间号
            console.log('get openid', res.openid) // 用户openid
            console.log('get share openid', res.share_openid) // 分享者openid，分享卡片进入场景才有
            console.log('get custom params', res.custom_params) // 开发者在跳转进入直播间页面时，页面路径上携带的自定义参数，这里传回给开发者
          }).catch(err => {
            console.log('get share params', err)
          })
      }
    }
  },
  //初始化
  onLaunch: function () {
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
    });
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: ' 更新提示 ',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })

    });
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    })

    // 检查登录session_key是否过期
    wx.checkSession({
      success() {
        // session_key 未过期，并且在本生命周期一直有效
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        //重新登录
        wx.setStorageSync('session_key', true);
        // wx.clearStorageSync();
      }
    });

    this.getFirstInit();

  },

  globalData: {
    deployUrl: 'https://pay.hnabmx.com/',
    webRoot: '/wemall',
    loginCentreId: 170,
    tempMid: '',//分享者id，推荐人id
    tempShopId: '',//分享门店id
    tempCentreId: '',//分享商户id
    cartTotal: '',//购物车角标
    IMAGE_PREFIX: 'http://pic.jinzhishenghuo.com',
    AK: '2HphuCaSCHkNvR2IZHb6Z1gPKozgCG6q',
    subscribeMessage: '3IX6YYBNKdAqlRetw6kRsNA6pPZnzauns0Dj2sSe97M',//订阅消息摸板id
  },

  /*
  * 封装接口请求
  * */
  requestUrl(options) {
    let u = this.globalData.deployUrl;
    if(options.load == 1){
      wx.showLoading({
        mask: true,
        title: '加载中'
      })
    }
    return new Promise((resolve, reject) => {
      wx.request({
        method: options.method,
        url: u + options.url,
        data: options.data,
        header: options.header ? options.header :{
          'Content-type':  options.method == 'GET' ? 'application/json' : 'application/x-www-form-urlencoded',
          'Accept': 'application/json',
          'Authorization': wx.getStorageSync('authToken') || 'empty-token'
        },
        dataType: 'json',
        success: function (res) {
          options.load == 1 ? wx.hideLoading() : '';
          if(res.data.code == 0){
            resolve(res);
          }else if(res.data.code == '401'){
            Dialog.alert({
              title: '提示',
              message: 'token已失效，请重新登录'
            }).then(() => {
              wx.navigateBack({ detail: 1 })
            })
          }
//          if(res.data.code == 0) resolve(res);
//          else wx.showToast({title: res.data.msg+'', icon: 'none'})
        },
        fail: function (err) {
          reject(err);
          options.load == 1 ? wx.hideLoading() : '';
          wx.showToast({
            title: "网络连接超时",
            icon: 'none',
            duration: 3000,
          })
        }
      })
    })
  },

  //app 全局属性监听cartTotal
  watch: function (method) {
    var obj = this.globalData
    Object.defineProperty(obj, 'cartTotal', {
      configurable: true,
      enumerable: true,
      set: function (value) {
        this._name = value;
        wx.setStorageSync('cartTotal',value);//存入缓存，tab页面调用，传给tabbar组件
        method(value);
      },
      get: function () {
        return this._name
      }
    })
  },


  //购物车角标
  getCartTotal () {
    let _this = this;
    let user = wx.getStorageSync('userInfo') ? JSON.parse(decodeURI(wx.getStorageSync('userInfo'))) : null;
    if(user == null) return;
    _this.requestUrl({
      method: 'GET',
      url: '/wxapi/cart/total',
      data: {
        centreId: user.centreId,
        memberId: user.id
      }
    }).then((res) => {
      _this.globalData.cartTotal = res.data.data

    })
  },

  //平台配置赋值
  setGlobalConfig (centreId) {
    let _this = this
    let user = this.getUser();
    if (wx.getStorageSync('globalConfig') == '') {
      this.requestUrl({
        method: 'GET',
        url: '/wxapi/global/config',
        data: {
          centreId: centreId ? centreId : user.centreId ? user.centreId : '',
        }
      }).then((res) => {
        wx.setStorageSync('globalConfig', JSON.stringify(res.data.data))
      })
    }
  },

  //如果已经登录set缓存
  getFirstInit(){
    let _this = this;
    let user = _this.getUser();
    if(user.id == null) return;

    this.requestUrl({
      method: 'GET',
      url: '/wxapi/firstinit',
      data: {
        memberId: user.id,
      },
      load: 0
    }).then(res =>{
      let tempUser = res.data.data;
      if(tempUser == '') return;

      tempUser.supplier = res.data.supplier;
      wx.setStorageSync('userInfo', JSON.stringify(tempUser))

      wx.setStorageSync('serverTime', res.data.time)

      if (tempUser.status === 9) {//黑名单
        wx.reLaunch({
          url: '/pages/login/forbidden/forbidden'
        })
      }

      if (res.data.shop != '')
        // wx.setStorageSync('shopInfo', JSON.stringify(res.data.shop))

      if (res.data.config)
        wx.setStorageSync('globalConfig', JSON.stringify(res.data.config))
    })
  },







  checkUser(){
    let uu = wx.getStorageSync('userInfo');
    if(uu == ''){
      wx.showToast({
        title: '未登录'
      })
      return true;
    };
  },

  //返回1 正常
  checkShop() {
    let shop = this.getShop();
    //不是门店或者禁用
    if ((shop.isteam !== 3) || (shop.status === 9)) {
      return -1;
    } else {
      if (shop.sleepTime) {//是否打烊
        const startTime = moment(shop.sleepStartTime).unix();
        const endTime = moment(shop.sleepEndTime).unix();
        const serverTime = moment().unix();
        shop.isSleep = (serverTime >= startTime) && (serverTime <= endTime);
      }

      return (shop.isSleep ? 0 : 1);
    }
  },

  getUser(){
    let user = null;
    if(wx.getStorageSync('userInfo') == ''){
      user = {
        upshopTid: null,
        id: null,
        centreId: null,
        myCode: null,
        isteam: null,

        credit2: 0,
        totalCommission: 0,
        income: 0,
      };
    } else {
      user = JSON.parse(wx.getStorageSync('userInfo'));
    }
    return user;
  },

  getShop(){
    let shop = null;
    if(wx.getStorageSync('shopInfo') == ''){
      shop = {
        isSleep: null,
        centerId: null,
        tXiaoqu: null,
      };
    } else {
      shop = JSON.parse(wx.getStorageSync('shopInfo'));
    }
    return shop;
  },

  getGlobalConfig(){
    let config = null;
    if(wx.getStorageSync('globalConfig') == ''){
      config = {
        expectedPickTime: 960,
      };
    } else {
      config = JSON.parse(wx.getStorageSync('globalConfig'));
    }
    return config;
  },

  getShareData(){
    let share = null;
    if(wx.getStorageSync('shareData') == ''){
      share = '';
    } else {
      share = JSON.parse(wx.getStorageSync('shareData'));
    }
    return share;
  },
  //吐司
  showToast: function (val) {
    wx.showToast({
      title: val,
      icon: "none",
      duration: 1500
    })
  },
})